package it.blueocean.acanto.taglibrary.jsp.taglib.tags.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang.StringUtils;
import org.dom4j.io.DocumentResult;
import org.dom4j.io.DocumentSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;

public class XmlUtils
{
	public static final String OPEN_START = "<";

	public static final String OPEN_END = "</";

	public static final String CLOSE = ">";

	public static final String NEW_LINE = "\n";

	public static final String SPACE = "    ";

	public static final String SPACE_1 = "        ";

	public static final String SPACE_2 = "            ";

	public static final String TAG_RS = "resultset";

	public static final String TAG_ROW = "row";

	public static final String ROWCOUNT = "rowcount";

	public static final String MOREPARAMETER = "moreparameter";

	public XmlUtils()
	{
	}

	public static String Node2String(Node node) throws TransformerException
	{
		DOMSource domsource = new DOMSource(node);
		StringWriter stringwriter = new StringWriter();
		StreamResult streamresult = new StreamResult(stringwriter);
		TransformerFactory transformerfactory = TransformerFactory.newInstance();
		Transformer transformer = transformerfactory.newTransformer();
		transformer.setOutputProperty("omit-xml-declaration", "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
		transformer.setOutputProperty("indent", "yes");
		transformer.setOutputProperty("encoding", "ISO-8859-1");
		transformer.transform(domsource, streamresult);
		return stringwriter.toString();
	}

	public static String applyStyleSheet(String s, String s1, Properties properties) throws Exception
	{
		StreamSource streamsource = new StreamSource(s1);
		return xmlToHtml(s, streamsource, properties);
	}

	public static String applyStyleSheet(String s, InputStream inputstream, Properties properties) throws Exception
	{
		StreamSource streamsource = new StreamSource(inputstream);
		return xmlToHtml(s, streamsource, properties);
	}

	public static String applyStyleSheet(Document document, InputStream inputstream, Properties properties)
			throws Exception
	{
		StreamSource streamsource = new StreamSource(inputstream);
		return xmlToHtml(document, streamsource, properties);
	}

	public static org.dom4j.Document applyStyleSheet(org.dom4j.Document document, InputStream inputstream,
			Properties properties) throws Exception
	{
		StreamSource streamsource = new StreamSource(inputstream);
		return xmlToHtml(document, streamsource, properties);
	}

	private static String xmlToHtml(String s, Source source, Properties properties) throws Exception
	{
		byte abyte0[] = s.getBytes();
		ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0);
		DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentbuilder = documentbuilderfactory.newDocumentBuilder();
		Document document = documentbuilder.parse(bytearrayinputstream);
		return xmlToHtml(document, source, properties);
	}

	private static String xmlToHtml(Document document, Source source, Properties properties) throws Exception
	{
		ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
		TransformerFactory transformerfactory = TransformerFactory.newInstance();
		Transformer transformer = transformerfactory.newTransformer(source);
		if(properties != null)
		{
			String s;
			for (Enumeration enumeration = properties.keys(); enumeration.hasMoreElements(); transformer.setParameter(
					s, properties.getProperty(s)))
				s = (String) enumeration.nextElement();
		}
		transformer.transform(new DOMSource(document), new StreamResult(bytearrayoutputstream));
		return bytearrayoutputstream.toString();
	}

	private static org.dom4j.Document xmlToHtml(org.dom4j.Document document, Source source, Properties properties)
			throws Exception
	{
		TransformerFactory transformerfactory = TransformerFactory.newInstance();
		Transformer transformer = transformerfactory.newTransformer(source);
		if(properties != null)
		{
			String s;
			for (Enumeration enumeration = properties.keys(); enumeration.hasMoreElements(); transformer.setParameter(
					s, properties.getProperty(s)))
				s = (String) enumeration.nextElement();
		}
		DocumentSource documentsource = new DocumentSource(document);
		DocumentResult documentresult = new DocumentResult();
		transformer.transform(documentsource, documentresult);
		return documentresult.getDocument();
	}

	public static String encodeXMLSpecialCharacter(String s)
	{
		if(s != null)
		{
			s = StringUtils.replace(s, "&", "&amp;");
			s = StringUtils.replace(s, ">", "&gt;");
			s = StringUtils.replace(s, "<", "&lt;");
			s = StringUtils.replace(s, "\"", "&quot;");
		}
		return s;
	}

	public static String markCDATA(String s)
	{
		for (int i = 0; i < s.length(); i++)
			if("<&".indexOf(s.substring(i, 1)) != -1)
				return (new StringBuilder()).append("<![CDATA[").append(s).append("]]>").toString();
		return s;
	}

	public static String createXmlContent(ResultSet resultset, Connection connection, String s, int i, int j, String s1)
			throws SQLException
	{
		SimpleDateFormat simpledateformat = new SimpleDateFormat(s1);
		StringBuffer stringbuffer = new StringBuffer();
		Object obj = null;
		Object obj1 = null;
		Object obj2 = null;
		ClobReader clobreader = new ClobReader(connection, resultset);
		stringbuffer.append("<resultset");
		stringbuffer.append(" ");
		stringbuffer.append("moreparameter");
		stringbuffer.append("=\"");
		stringbuffer.append(s);
		stringbuffer.append("\"");
		stringbuffer.append(">");
		ResultSetMetaData resultsetmetadata = resultset.getMetaData();
		int k = resultsetmetadata.getColumnCount();
		int l = 0;
		do
		{
			if(!resultset.next())
				break;
			if(++l >= i && (j < 0 || l < j + i && j > 0))
			{
				stringbuffer.append("\n");
				stringbuffer.append("        ");
				stringbuffer.append("<row");
				stringbuffer.append((new StringBuilder()).append(" rowcount='").append(l).append("'").append(">")
						.toString());
				for (int i1 = 1; i1 < k + 1; i1++)
				{
					stringbuffer.append("\n");
					stringbuffer.append("            ");
					String s2 = resultsetmetadata.getColumnName(i1);
					stringbuffer.append((new StringBuilder()).append("<").append(s2).append(">").toString());
					Object obj3 = resultset.getObject(i1);
					String s3 = resultsetmetadata.getColumnTypeName(i1);
					String s4;
					if(obj3 != null)
					{
						if(obj3 instanceof Timestamp)
							s4 = simpledateformat.format((Timestamp) obj3);
						else
						if((obj3 instanceof Clob) || s3.equals("CLOB") || s3.equals("BLOB"))
							s4 = clobreader.getText(i1);
						else
							s4 = obj3.toString().trim();
					}
					else
					{
						s4 = "";
					}
					stringbuffer.append(encodeXMLSpecialCharacter(s4));
					stringbuffer.append((new StringBuilder()).append("</").append(s2).append(">").toString());
				}

				stringbuffer.append("\n");
				stringbuffer.append("        ");
				stringbuffer.append("</row>");
			}
		}
		while (true);
		stringbuffer.append("\n");
		stringbuffer.append("    ");
		stringbuffer.append("</resultset>");
		clobreader.close();
		return stringbuffer.toString();
	}

	public static void appendSimpleTextElement(Node node, String s, String s1)
	{
		Document document = node.getOwnerDocument();
		Element element = document.createElement(s);
		if(s1 != null)
		{
			org.w3c.dom.Text text = document.createTextNode(s1);
			element.appendChild(text);
		}
		node.appendChild(element);
	}
}
